package com.yanqu.road.server.cmd;

import com.yanqu.road.connect.AgentServerLinkControl;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.activity.ActivityDisperseGoldProto;
import com.yanqu.road.player.Player;
import com.yanqu.road.player.PlayerControl;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;
import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

@Cmd(code = Protocol.A_ACTIVITY_DISPERSE_GOLD_TRANSFER, desc = "世界消息转发-活动送财")
public class ActivityDisperseGoldTransferCmd implements Command {

	private static Logger logger = LogManager.getLogger(ActivityDisperseGoldTransferCmd.class.getName());

	@Override
	public void execute(ChannelHandlerContext ctx, YanQuMessage packet) throws Exception {
		ActivityDisperseGoldProto.CrossActivityDisperseGoldRespMsg respMsg = ActivityDisperseGoldProto.CrossActivityDisperseGoldRespMsg.parseFrom(packet.getBytes());
		logger.info("activity disperse gold id:{}, begin time:{}", respMsg.getGoldInfo().getDisperseId(), respMsg.getGoldInfo().getBeginTime());
		List<Long> userIdList = new ArrayList<>();
		Map<Long, Player> allPlayer = new HashMap<>(PlayerControl.getOnlinePlayerMap());
		for (Entry<Long, Player> dataEntry : allPlayer.entrySet()) {
            ActivityDisperseGoldProto.ActivityDisperseGoldClientRespMsg.Builder builder = ActivityDisperseGoldProto.ActivityDisperseGoldClientRespMsg.newBuilder();
            builder.setGoldInfo(respMsg.getGoldInfo());
            YanQuMessage msg = YanQuMessageUtils.buildMessageByte(Protocol.U_ACTIVITY_DISPERSE_GOLD_SYNC, builder.build().toByteArray());
			msg.setPlayerId(dataEntry.getKey());
			msg.setLen(packet.getLen());
			AgentServerLinkControl.routeClient(msg);
			userIdList.add(dataEntry.getKey());
		}
		logger.info("activity disperse gold id:{}, to users: {}", respMsg.getGoldInfo().getDisperseId(), StringUtils.listToString(userIdList, ","));
	}
}